package edu.gduf.parcel.sal.sms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

import edu.gduf.parcel.common.constant.ParcelConstant;
import edu.gduf.parcel.repository.SysConfigMapper;
import edu.gduf.parcel.sal.sms.vo.ValidateCode;

@Component("smsPlugin")
public class SMSPlugin {

	private static final String PARAM_ITEM = "SMS";
	private static Logger logger = LoggerFactory.getLogger(SMSPlugin.class);
	@Autowired
	private SysConfigMapper sysConfigMapper;

	/**
	 * 发送验证码短信(支持发送多个电话号码)
	 * 
	 * @param recNum
	 *            【重要】批量发送（一次传递多个号码eg:1381111111,1382222222）会产生相应的延迟，触达时间要求高的建议单条发送
	 * @return
	 */
	public String sendValidateSMS(String recNum, ValidateCode code) {
		String result = "";
		try {
			TaobaoClient client = new DefaultTaobaoClient(this.getUrl(), this.getAppkey(), this.getSecret());
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			// 设置短信类型的文本信息
			req.setSmsType(ParcelConstant.SMS.SMS_TYPE_NORMAL);
			// 设置短信签名
			req.setSmsFreeSignName(ParcelConstant.SMS.SMS_FREE_SIGN_NAME);
			String smsParamString = JSON.toJSONString(code);
			// 设置短信模板内容
			req.setSmsParamString(smsParamString);
			// 设置接收手机
			req.setRecNum(recNum);
			// 设置短信模板编号
			req.setSmsTemplateCode(ParcelConstant.SMS.VALID_TEMPLATE_CODE);
			// 发送短信
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
			result = rsp.getBody();
		} catch (ApiException e) {
			logger.error("发送短信发生错误：原因", e);
		}
		return result;
	}

	private String getUrl() {
		return sysConfigMapper.getSysParamValue(PARAM_ITEM, "API_URL");
	}

	private String getAppkey() {
		return sysConfigMapper.getSysParamValue(PARAM_ITEM, "APP_KEY");
	}

	private String getSecret() {
		return sysConfigMapper.getSysParamValue(PARAM_ITEM, "APP_SECRET");
	}
}
